package zsw.reflect;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class CglibTestAnnotation implements MethodInterceptor {
	
	private Object target;
	
	private Object proxy;
	
	public Object getInstance(Object o) {
		this.target=o;
		Enhancer en=new Enhancer();
		en.setSuperclass(o.getClass());
		en.setCallback(this);
		Object p= en.create();
		proxy=p;
		return p;
	}

	@Override
	public Object intercept(Object paramObject, Method paramMethod, Object[] paramArrayOfObject,
			MethodProxy paramMethodProxy) throws Throwable {
		Class<? extends Object> class1 = paramObject.getClass();
	
		System.out.println("是否是代理对象"+(paramObject==target));
		System.out.println("是否是代理对象"+(paramObject==proxy));
		System.out.println(paramObject.getClass());
		System.out.println("方法paramMethod:"+paramMethod.getDeclaringClass());
		
		//通过反射获取所有的方法，判断方法是是有有注解，并且这个注解的值是否是yes，如果是，我们就开启代理的功能
		HasPrimesission annotation = paramMethod.getAnnotation(HasPrimesission.class);
		String value = "";
		     if(annotation!=null)
		    	 value=	annotation.value();
		Object invokeSuper=null;
		if("yes".equalsIgnoreCase(value)) {
			System.out.println("开始代理");
			 invokeSuper = paramMethodProxy.invokeSuper(paramObject, paramArrayOfObject);
             System.out.println("代理结束");
		}else {
			invokeSuper = paramMethodProxy.invokeSuper(paramObject, paramArrayOfObject);
		}
		return invokeSuper;
	}
	
	public static void main(String[] args) {
		CglibTestAnnotation s=new CglibTestAnnotation();
		TestAnnotation t=new TestAnnotation();
		TestAnnotation instance = (TestAnnotation) s.getInstance(t);
		String hasPremission = instance.hasPremission("zsw");
		System.out.println("执行成功"+hasPremission);
		
		/*String run = instance.run("run");
		System.out.println("执行成功"+run);
		
		
		String say = instance.say("hellp");
		System.out.println("执行成功"+say);*/
	}

}
